package com.adam.example.aggregation.bucket;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.Buckets;
import co.elastic.clients.elasticsearch._types.aggregations.IpRangeAggregate;
import co.elastic.clients.elasticsearch._types.aggregations.IpRangeBucket;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.adam.example.ElasticsearchClientHolder;
import com.adam.example.util.JsonUtil;

import java.io.IOException;

/**
 * 执行报错：反序列化失败
 */
public class IpRangeAggregationExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient elasticsearchClient = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();

        SearchRequest searchRequest = SearchRequest.of(builder -> builder
                        .index("test_ip")
                        .size(0)
                        .aggregations("agg", aggregationBuilder -> aggregationBuilder
                                .ipRange(ipRangeAggregationBuilder -> ipRangeAggregationBuilder
                                        .field("ip")
                                        .ranges(ipRangeAggregationRangeBuilder -> ipRangeAggregationRangeBuilder
                                                .to("10.0.0.5")
                                        )
                                        .ranges(ipRangeAggregationRangeBuilder -> ipRangeAggregationRangeBuilder
                                                .from("10.0.0.5")
                                        )
                                )
                        )
        );
        System.out.println(JsonUtil.searchRequestToJson(searchRequest, elasticsearchClient));
        SearchResponse<Void> searchResponse = elasticsearchClient.search(searchRequest, Void.class);
        Aggregate aggregate = searchResponse.aggregations().get("agg");
        IpRangeAggregate ipRangeAggregate = aggregate.ipRange();
        Buckets<IpRangeBucket> buckets = ipRangeAggregate.buckets();
        System.out.println(buckets.isArray());

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
